package com.czy.owner.ui.order;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.czy.owner.R;
import com.czy.owner.adapter.GridImageAdapter;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.CashierInputFilter;
import com.czy.owner.utils.DataCleanManager;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.utils.glide.config.GlideCacheConfig;
import com.czy.owner.widget.ActionSheetDialog;
import com.czy.owner.widget.FullyGridLayoutManager;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.FunctionOptions;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2017/6/6 0006.
 * 退款页面
 */
public class RefundActivity extends BaseActivity {
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    saveImage(bitmap);
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(currentFile.toString());
                    localMedia.setType(1);
                    MyLog.e("yang",currentFile.toString());
                    selectMedia.add(localMedia);
                    adapter.notifyDataSetChanged();
                    break;
            }

        }
    };


    @BindView(R.id.spinner_refund_type)
    Spinner spinnerRefundType;
    @BindView(R.id.ll_refund_type)
    LinearLayout llRefundType;
    @BindView(R.id.spinner_receive_status)
    Spinner spinnerReceiveStatus;
    @BindView(R.id.ll_receive_status)
    LinearLayout llReceiveStatus;
    @BindView(R.id.spinner_refund_reason)
    Spinner spinnerRefundReason;
    @BindView(R.id.ll_refund_reason)
    LinearLayout llRefundReason;
    @BindView(R.id.et_refund_money)
    EditText etRefundMoney;
    @BindView(R.id.tv_refund_money)
    TextView tvRefundMoney;
    @BindView(R.id.ll_refund_money)
    LinearLayout llRefundMoney;
    @BindView(R.id.et_refund_note)
    EditText etRefundNote;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.btn_commit_apply)
    Button btnCommitApply;
    private String refundTitle;
    private int refundsOrderId;
    private int userOrderId;
    private String goodsId;
    private String specGroupKey;
    private double applyRefundsAmount;
    private boolean isEdit = false;
    private String orderStatus;
    private int orderItemId;

    private String refundsType = "";//退款类型
    private String status;//收货状态
    private String mReason;//退款原因
    private String note;
    private ArrayList<String> picList = new ArrayList<>();
    private String mApplyRefundsReason;
    private String mRefundsType;
    private int refundReasonIndex;
    private Bitmap bitmap = null;
    private File currentFile = null;
    // 退款原因
    String[] mArrayReason = new String[]{"不喜欢", "空包裹", "货物破损已拒签", "未按约定时间发货",
            "快递/物流一直未送到", "快递/物流无跟踪记录"};
    String[] mArrayReason2 = new String[]{"质量问题", "商品成分描述不符", "生产日期/保质期与商品不符",
            "图片/产地/批号/规格等描述不符", "快递/少件", "发错货", "商品破损", "未按时间发货", "发票问题", "七天无理由退货"};


    //    图片选择相关
    private GridImageAdapter adapter;
    private int selectMode = FunctionConfig.MODE_MULTIPLE;
    private int maxSelectNum = 5;// 图片最大可选数量
    private int selectType = FunctionConfig.TYPE_IMAGE;
    private int copyMode = FunctionConfig.CROP_MODEL_DEFAULT;
    private boolean enablePreview = true;
    private boolean isPreviewVideo = true;
    private boolean selectImageType = false;
    private int cropW = 0;
    private int cropH = 0;
    private int maxB = 0;
    private int compressW = 0;
    private int compressH = 0;
    private boolean isCompress = false;
    private boolean isCheckNumMode = true;
    private int compressFlag = 1;// 1 系统自带压缩 2 luban压缩
    private List<LocalMedia> selectMedia = new ArrayList<>();
    private int themeStyle;
    private int previewColor, completeColor, previewBottomBgColor, previewTopBgColor, bottomBgColor, checkedBoxDrawable;
    private boolean clickVideo = false;
    private boolean isFlagCamera = true;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_refund;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        refundTitle = getIntent().getStringExtra("refundTitle");
        spinnerRefundType.setClickable(false);
        spinnerRefundType.setEnabled(false);
        getToolbarTitle().setText(refundTitle);
        isEdit = getIntent().getBooleanExtra("isEdit", false);
        if (isEdit) {
            refundsOrderId = getIntent().getIntExtra("refundsOrderId", 0);
        }
        orderItemId = getIntent().getIntExtra("orderItemId",0);
        userOrderId = getIntent().getIntExtra("userOrderId", 0);
        goodsId = getIntent().getStringExtra("goodsId");
        specGroupKey = getIntent().getStringExtra("specGroupKey");
        applyRefundsAmount = Double.parseDouble(String.format("%.2f", getIntent().getDoubleExtra("applyRefundsAmount", 0.00)));
        orderStatus = getIntent().getStringExtra("orderStatus");
        InputFilter[] filters = {new CashierInputFilter(9), new InputFilter.LengthFilter(9)};
        etRefundMoney.setFilters(filters);
        etRefundMoney.addTextChangedListener(new RefundActivity.MyetRefundMoney());
        initSpinner();


        if (isEdit) {
            note = getIntent().getStringExtra("note");
            if (!TextUtils.isEmpty(note)) {
                etRefundNote.setText(note);
            }
            picList = getIntent().getStringArrayListExtra("picList");

            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (picList != null && picList.size() > 0) {
                        for (int i = 0; i < picList.size(); i++) {
                            MyLog.e("yang", picList.get(i));
                            try {
                                bitmap = Glide.with(RefundActivity.this)
                                        .load(picList.get(i))
                                        .asBitmap()
                                        .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                        .get();
                                Message msg = new Message();
                                msg.what = 0;
                                msg.getData().putString("picUrl", picList.get(i));
                                handler.sendMessage(msg);
                            } catch (Exception e) {

                            }
                        }
                    }
                }
            }).start();


            mApplyRefundsReason = getIntent().getStringExtra("mApplyRefundsReason");
            mRefundsType = getIntent().getStringExtra("mRefundsType");

            if (mRefundsType.equals("returnGoods")) {   //退货
//                spinnerRefundType.setSelection(0);
                spinnerReceiveStatus.setSelection(0);
                for (int i = 0; i < mArrayReason2.length; i++) {
                    String reason = mArrayReason2[i];
                    if (mApplyRefundsReason.equals(reason)) {
                        MyLog.e("yang", "ii====" + i);
                        refundReasonIndex = i;
                        break;
                    }

                }
            } else if (mRefundsType.equals("receiveGoods")) {  //收货退款
//                spinnerRefundType.setSelection(1);
                spinnerReceiveStatus.setSelection(0);

                for (int i = 0; i < mArrayReason2.length; i++) {
                    String reason = mArrayReason2[i];
                    if (mApplyRefundsReason.equals(reason)) {
                        MyLog.e("yang", "ii====" + i);
                        refundReasonIndex = i;
                        break;
                    }

                }

            } else if (mRefundsType.equals("notReceiveGoods")) { // 未收货退款
//                spinnerRefundType.setSelection(1);
                spinnerReceiveStatus.setSelection(1);

                for (int i = 0; i < mArrayReason.length; i++) {
                    String reason = mArrayReason[i];
                    if (mApplyRefundsReason.equals(reason)) {
                        MyLog.e("yang", "ii====" + i);
                        refundReasonIndex = i;
                        break;
                    }

                }
            }

            MyLog.e("yang", mApplyRefundsReason + "===========" + mRefundsType);

        }


        etRefundMoney.setText(String.format("%.2f", applyRefundsAmount));
        etRefundMoney.setSelection(etRefundMoney.getText().toString().length());
        tvRefundMoney.setText("￥最多" + String.format("%.2f", applyRefundsAmount));


//        图片选择器相关
        FullyGridLayoutManager manager = new FullyGridLayoutManager(RefundActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(RefundActivity.this, onAddPicClickListener);
        adapter.setList(selectMedia);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                switch (selectType) {
                    case FunctionConfig.TYPE_IMAGE:
                        // 预览图片 可长按保存 也可自定义保存路径
                        //PictureConfig.getInstance().externalPicturePreview(MainActivity.this, "/custom_file", position, selectMedia);
                        PictureConfig.getInstance().externalPicturePreview(RefundActivity.this, position, selectMedia);
                        break;
                    case FunctionConfig.TYPE_VIDEO:
                        // 预览视频
                        if (selectMedia.size() > 0) {
                            PictureConfig.getInstance().externalPictureVideo(RefundActivity.this, selectMedia.get(position).getPath());
                        }
                        break;
                }

            }
        });
    }

    @Override
    protected void updateViews() {

    }

    //    输入金额不能大于退款金额
    class MyetRefundMoney implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String refundMoney = etRefundMoney.getText().toString().trim();
            if (TextUtils.isEmpty(refundMoney)) {
                refundMoney = "0.00";
            }


            if (Double.parseDouble(refundMoney) > applyRefundsAmount) {
                PhoneUtils.ShowToastMessage(RefundActivity.this, "输入金额不能大于退款金额");
                int selectionStart = etRefundMoney.getSelectionStart();
                int selectionEnd = etRefundMoney.getSelectionEnd();
                s.delete(selectionStart - 1, selectionEnd);
                return;
            }
        }
    }


    @OnClick(R.id.tv_refund_money)
    public void refundMoney(View view) {
        etRefundMoney.setText(String.format("%.2f", applyRefundsAmount));
    }

    @OnClick(R.id.btn_commit_apply)
    public void commintApply(View view) {
        String returnMoney = etRefundMoney.getText().toString().trim();
        String note = etRefundNote.getText().toString().trim();
        if (TextUtils.isEmpty(returnMoney)) {
            PhoneUtils.ShowToastMessage(RefundActivity.this, "请输入退款金额");
            etRefundMoney.requestFocus();
            btnCommitApply.setEnabled(true);
            return;
        }

        if (Double.parseDouble(returnMoney) == 0) {
            PhoneUtils.ShowToastMessage(RefundActivity.this, "退款金额必须大于0");
            etRefundMoney.requestFocus();
            btnCommitApply.setEnabled(true);
            return;
        }

        applyReturn(returnMoney, note);
    }


    private void applyReturn(String returnMoney, String note) {
        mLoadView.ShowLoadView();
        btnCommitApply.setEnabled(false);
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_ORDERS_APPLYRETURN);

        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(RefundActivity.this).getSession());
        if (refundsOrderId != 0) {
            params.addBodyParameter("refundsOrderId", refundsOrderId + "");
        }
        params.addBodyParameter("userOrderId", userOrderId + "");
        params.addBodyParameter("goodsId", goodsId + "");
        params.addBodyParameter("specGroupKey", specGroupKey);
        params.addBodyParameter("refundsType", refundsType);
        params.addBodyParameter("applyRefundsAmount", returnMoney);
        params.addBodyParameter("applyRefundsReason", mReason, "UTF-8");
        params.addBodyParameter("applyRefundsNote", note, "UTF-8");
        params.addBodyParameter("orderItemId",orderItemId+"");
        params.setMultipart(true);
        MyLog.e("yang", "params===" + params.toString());
        try {
            if (selectMedia.size() > 0) {
                for (int i = 0; i < selectMedia.size(); i++) {
                    params.addBodyParameter("file" + (i + 1), new FileInputStream(new File(selectMedia.get(i).getPath())), "img/jpg", "pic" + i + ".jpg");
                    MyLog.e("yang", "图片地址==" + selectMedia.get(i).getPath() + "\n图片个数==" + selectMedia.size());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    mLoadView.CancleLoadView();
                    PhoneUtils.ShowToastMessage(RefundActivity.this, "提交成功,请等待");
                    btnCommitApply.setEnabled(true);

                    Intent intent = new Intent();
                    intent.setAction(OrderActivity.orderAction);
                    intent.putExtra("currentId", 5);
                    sendBroadcast(intent);

                    RxBus.getDefault().post(Constants.RETURNORDER, new CommonEvent("申请退款"));
                    finish();

                } else {
                    mLoadView.CancleLoadView();
                    PhoneUtils.ShowToastMessage(RefundActivity.this, exp);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
                btnCommitApply.setEnabled(true);
            }
        });
    }

    private void initSpinner() {
        //退款类型
        String[] mArrayType = new String[]{"退款退货"};
        ArrayAdapter<String> spinnerTypeAdapter = new ArrayAdapter<>(RefundActivity.this, android.R.layout.simple_spinner_item, mArrayType);
        spinnerTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerRefundType.setAdapter(spinnerTypeAdapter);
        spinnerRefundType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                if (orderStatus.equals("waitDelivery")) {
//                    spinnerRefundType.setSelection(1);
//                    spinnerRefundType.setClickable(false);
//                    spinnerRefundType.setEnabled(false);
//                } else {
//                    switch (i) {
//                        case 0:
//                            refundsType = "returnGoods";
//                            spinnerReceiveStatus.setSelection(0);
//                            spinnerReceiveStatus.setClickable(false);
//                            spinnerReceiveStatus.setEnabled(false);
//                            break;
//                        case 1:
//                            spinnerReceiveStatus.setClickable(true);
//                            spinnerReceiveStatus.setEnabled(true);
//                            refundsType = "receiveGoods";
//                            break;
//
//                    }
//                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        // 收货状态
        String[] mArrayStatus = new String[]{"已收货", "未收货"};
        ArrayAdapter<String> spinnerStatusAdapter = new ArrayAdapter<>(RefundActivity.this, android.R.layout.simple_spinner_item, mArrayStatus);
        spinnerStatusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerReceiveStatus.setAdapter(spinnerStatusAdapter);
        spinnerReceiveStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (orderStatus.equals("waitDelivery")) {
                    refundsType = "notReceiveGoods";
                    spinnerReceiveStatus.setSelection(1);
                    spinnerReceiveStatus.setClickable(false);
                    spinnerReceiveStatus.setEnabled(false);
                } else {
//                    if (spinnerRefundType.getSelectedItemId() == 1) {
                        switch (i) {
                            case 0:
                                refundsType = "receiveGoods";
                                break;
                            case 1:
                                refundsType = "notReceiveGoods";
                                break;
                        }

//                    }
                }

                if (refundsType.equals("notReceiveGoods")) {
                    ArrayAdapter<String> spinnerReasonAdapter = new ArrayAdapter<>(RefundActivity.this, android.R.layout.simple_spinner_item, mArrayReason);
                    spinnerReasonAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinnerRefundReason.setAdapter(spinnerReasonAdapter);
                } else {
                    ArrayAdapter<String> spinnerReasonAdapter = new ArrayAdapter<>(RefundActivity.this, android.R.layout.simple_spinner_item, mArrayReason2);
                    spinnerReasonAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinnerRefundReason.setAdapter(spinnerReasonAdapter);
                }

                MyLog.e("yang","refundsType=="+refundsType);
            }



            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        spinnerRefundReason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (refundsType.equals("notReceiveGoods")) {
                    switch (i) {
                        case 0:
                            mReason = "不喜欢";
                            break;
                        case 1:
                            mReason = "空包裹";
                            break;
                        case 2:
                            mReason = "货物破损已拒签";
                            break;
                        case 3:
                            mReason = "未按约定时间发货";
                            break;
                        case 4:
                            mReason = "快递/物流一直未送到";
                            break;
                        case 5:
                            mReason = "快递/物流无跟踪记录";
                            break;
                    }
                } else {
                    switch (i) {
                        case 0:
                            mReason = "质量问题";
                            break;
                        case 1:
                            mReason = "商品成分描述不符";
                            break;
                        case 2:
                            mReason = "生产日期/保质期与商品不符";
                            break;
                        case 3:
                            mReason = "图片/产地/批号/规格等描述不符";
                            break;
                        case 4:
                            mReason = "快递/少件";
                            break;
                        case 5:
                            mReason = "发错货";
                            break;
                        case 6:
                            mReason = "商品破损";
                            break;
                        case 7:
                            mReason = "未按时间发货";
                            break;
                        case 8:
                            mReason = "发票问题";
                            break;
                        case 9:
                            mReason = "七天无理由退货";
                            break;
                    }
                }
                if (isEdit) {
                    spinnerRefundReason.setSelection(refundReasonIndex);
                    isEdit = false;
                }

            }


            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


    }


    /**
     * 删除图片回调接口
     */

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick(final int type, int position) {
            switch (type) {
                case 0:
                    new ActionSheetDialog(RefundActivity.this).builder()
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true)
                            .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.ThemeColor,
                                    new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            isFlagCamera = true;
                                            cameraPhoto(true);

                                        }
                                    })
                            .addSheetItem("相册", ActionSheetDialog.SheetItemColor.ThemeColor,
                                    new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            isFlagCamera = false;
                                            cameraPhoto(false);
                                        }
                                    }).show();
                    break;


                case 1:
                    // 删除图片
                    selectMedia.remove(position);
                    adapter.notifyItemRemoved(position);
                    break;
            }
        }
    };


    private void cameraPhoto(boolean model) {
        // 进入相册
        themeStyle = ContextCompat.getColor(RefundActivity.this, R.color.appThemeColor);
        if (selectImageType) {
            checkedBoxDrawable = R.drawable.select_cb;
        } else {
            checkedBoxDrawable = 0;
        }

        if (isCheckNumMode) {
            // QQ 风格模式下 这里自己搭配颜色
            previewColor = ContextCompat.getColor(RefundActivity.this, R.color.blue);
            completeColor = ContextCompat.getColor(RefundActivity.this, R.color.blue);
        }

        FunctionOptions options = new FunctionOptions.Builder()
                .setType(selectType) // 图片or视频 FunctionConfig.TYPE_IMAGE  TYPE_VIDEO
                .setCropMode(copyMode) // 裁剪模式 默认、1:1、3:4、3:2、16:9
                .setCompress(isCompress) //是否压缩
                .setEnablePixelCompress(true) //是否启用像素压缩
                .setEnableQualityCompress(true) //是否启质量压缩
                .setMaxSelectNum(maxSelectNum) // 可选择图片的数量
                .setMinSelectNum(0)// 图片或视频最低选择数量，默认代表无限制
                .setSelectMode(selectMode) // 单选 or 多选
                .setShowCamera(false) //是否显示拍照选项 这里自动根据type 启动拍照或录视频
                .setEnablePreview(enablePreview) // 是否打开预览选项
                .setEnableCrop(false) // 是否打开剪切选项
                .setCircularCut(false)// 是否采用圆形裁剪
                .setPreviewVideo(isPreviewVideo) // 是否预览视频(播放) mode or 多选有效
                .setCheckedBoxDrawable(checkedBoxDrawable)
                .setRecordVideoDefinition(FunctionConfig.HIGH) // 视频清晰度
                .setRecordVideoSecond(60) // 视频秒数
                .setCustomQQ_theme(0)// 可自定义QQ数字风格，不传就默认是蓝色风格
                .setGif(false)// 是否显示gif图片，默认不显示
                .setCropW(cropW) // cropW-->裁剪宽度 值不能小于100  如果值大于图片原始宽高 将返回原图大小
                .setCropH(cropH) // cropH-->裁剪高度 值不能小于100 如果值大于图片原始宽高 将返回原图大小
                .setMaxB(maxB) // 压缩最大值 例如:200kb  就设置202400，202400 / 1024 = 200kb
                .setPreviewColor(previewColor) //预览字体颜色
                .setCompleteColor(completeColor) //已完成字体颜色
                .setPreviewBottomBgColor(previewBottomBgColor) //预览图片底部背景色
                .setPreviewTopBgColor(previewTopBgColor)//预览图片标题背景色
                .setBottomBgColor(bottomBgColor) //图片列表底部背景色
                .setGrade(Luban.THIRD_GEAR) // 压缩档次 默认三档
                .setCheckNumMode(isCheckNumMode)
                .setCompressQuality(100) // 图片裁剪质量,默认无损
                .setImageSpanCount(4) // 每行个数
                .setVideoS(0)// 查询多少秒内的视频 单位:秒
                .setSelectMedia(selectMedia) // 已选图片，传入在次进去可选中，不能传入网络图片
                .setCompressFlag(compressFlag) // 1 系统自带压缩 2 luban压缩
                .setCompressW(compressW) // 压缩宽 如果值大于图片原始宽高无效
                .setCompressH(compressH) // 压缩高 如果值大于图片原始宽高无效
                .setThemeStyle(themeStyle) // 设置主题样式
                .setNumComplete(false) // 0/9 完成  样式
                .setClickVideo(clickVideo)// 点击声音
//                            .setPicture_title_color(ContextCompat.getColor(RefundActivity.this, R.color.black)) // 设置标题字体颜色
//                            .setPicture_right_color(ContextCompat.getColor(RefundActivity.this, R.color.black)) // 设置标题右边字体颜色
//                            .setLeftBackDrawable(R.mipmap.back2) // 设置返回键图标
//                            .setStatusBar(ContextCompat.getColor(RefundActivity.this, R.color.white)) // 设置状态栏颜色，默认是和标题栏一致
//                            .setImmersive(false)// 是否改变状态栏字体颜色(黑色)
                .create();

        if (model) {
            // 先初始化参数配置 拍照
            PictureConfig.getInstance().init(options).startOpenCamera(RefundActivity.this, resultCallback);
        } else {
            // 先初始化参数配置，启动相册
            PictureConfig.getInstance().init(options).openPhoto(RefundActivity.this, resultCallback);
        }

    }


    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            // 多选回调
            if (isFlagCamera) {
                selectMedia.addAll(resultList);
            } else {
                selectMedia = resultList;
            }

            MyLog.e("callBack_result", selectMedia.size() + "");
            LocalMedia media = resultList.get(0);
            if (media.isCut() && !media.isCompressed()) {
                // 裁剪过
                String path = media.getCutPath();
            } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                String path = media.getCompressPath();
            } else {
                // 原图地址
                String path = media.getPath();
            }
            if (selectMedia != null) {
                adapter.setList(selectMedia);
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onSelectSuccess(LocalMedia media) {
            // 单选回调
            selectMedia.add(media);
            if (selectMedia != null) {
                adapter.setList(selectMedia);
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name))
                    return getApplicationContext().getSystemService(name);
                return super.getSystemService(name);
            }
        });
    }


    public void saveImage(Bitmap bmp) {
        // 首先保存图片
       // File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        File file = GlideCacheConfig.storageDirectory;
        String fileName = GlideCacheConfig.GLIDE_CARCH_DIR;
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String picName = System.currentTimeMillis() + ".jpg";
        currentFile = new File(appDir, picName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
